package org.example.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtils {

    private   HibernateUtils(){};

    public static HibernateUtils instance = new HibernateUtils();

    public static HibernateUtils getInstance(){
        return  instance;
    }
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        if (sessionFactory == null){

            StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("/hibernate.cfg.xml").build();
            //2. 根据服务注册类创建一个元数据资源集，同时构建元数据并生成应用一般唯一的的session工厂
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();


        }
        return  sessionFactory;

    }

    public Session getSession(){
        return getSessionFactory().getCurrentSession();
    }
}
